package com.xywzxw.niushop.controller;

import com.alibaba.fastjson.JSON;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonQueryOrderApi.commonGetOrderTraceV1.CommonOrderTraceDetail;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCreateLopResponse;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersTraceQueryLopResponse;
import com.xywzxw.niushop.entity.*;
import com.xywzxw.niushop.mapper.ShopAddressMapper;
import com.xywzxw.niushop.mapper.ShopConfigMapper;
import com.xywzxw.niushop.mapper.ShopOrderDeliveryMapper;
import com.xywzxw.niushop.mapper.ShopOrderMapper;
import com.xywzxw.niushop.utils.JDExpressModel;
import com.xywzxw.niushop.utils.JDExpressTools;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/adminapi/order")
public class OrderController {
    @Resource
    ShopOrderMapper shopOrderMapper;
    @Resource
    ShopOrderDeliveryMapper deliveryMapper;
    @Resource
    ShopAddressMapper addressMapper;

    @Resource
    ShopConfigMapper configMapper;


    private Map<String,String> getConfig(){
        Map<String,Object> map=new HashMap<>();
        map.put("config_key", "JD_CONFIG");
        List<ShopConfig> shopConfigs = configMapper.selectByMap(map);
        if(!shopConfigs.isEmpty()){
            String value = shopConfigs.get(0).getValue();
            return JSON.parseObject(value, Map.class);
        }
        return null;
    }

    @PostMapping("getOrderTrace/{waybillCode}")
    private CommonResult<Object> getOrderTrace(@PathVariable("waybillCode") String waybillCode) throws LopException {
        Map<String, String> config = getConfig();
        EcapV1OrdersTraceQueryLopResponse response = new JDExpressTools().getOrderTrace(config.get("appKey"),config.get("appSecret"),config.get("accessToken"),waybillCode);
        if (response.getCode().equals("0")){
            if (response.getResult().getData() != null){
                CommonResult<Object> success = CommonResult.success(response.getResult().getData().getTraceDetails());
                success.setCode(1);
                return success;
            }else {
                return CommonResult.failed(response.getResult().getMsg());
            }
        }else {
            return CommonResult.failed("物流单号查询失败");
        }
    }
    /**
     *
     * @return
     */
    @PostMapping("createOrder")
    private CommonResult<Object> createOrder(@RequestBody Map<String,String> json) {
        String orderId = json.get("orderId");
        String type = json.get("type");
        Long pickupStartTime = Long.valueOf(json.get("pickupStartTime") == null ? "0" : json.get("pickupStartTime"));
        Long pickupEndTime = Long.valueOf(json.get("pickupEndTime") == null ? "0" : json.get("pickupEndTime"));
        JDExpressModel model = new JDExpressModel();
        HashMap<String, Object> map = new HashMap<>();
        map.put("order_id", orderId);
        List<ShopOrder> orders = shopOrderMapper.selectByMap(map);
        if (orders != null && !orders.isEmpty()) {
            ShopOrder shopOrder = orders.get(0);
            if (type.equals("none_express")){
                shopOrder.setStatus(3);
                shopOrder.setResend(1);
                shopOrderMapper.updateById(shopOrder);
                return CommonResult.success(null);
            }

            // 调用京东物流
            model.setOrderId(shopOrder.getOrderNo()+"01");
            model.setVolume(10);
            model.setWeight(1);
            Map<String, String> config = getConfig();
            // 基础配置
            assert config != null;
            model.setAppKey(config.get("appKey"));
            model.setAccessToken(config.get("accessToken"));
            model.setAppSecret(config.get("appSecret"));
            model.setCustomCode(config.get("customCode"));
            if (pickupStartTime > 0){
                model.setPickupStartTime(pickupStartTime);
            }
            if (pickupEndTime > 0){
                model.setPickupEndTime(pickupEndTime);
            }
            System.out.println(config);

            // 配置发件人信息
            model.setSendUser(shopOrder.getTakerName());
            model.setSendMobile(shopOrder.getTakerMobile());
            model.setSendAddress(shopOrder.getTakerFullAddress());

            // 获取并配置收件人信息
            ShopAddress address = addressMapper.selectById(1);
            model.setReceiveUser(address.getContactName());
            model.setReceiveMobile(address.getMobile());
            model.setReceiveAddress(address.getFullAddress());

            // 生成物流单号
            EcapV1OrdersCreateLopResponse jdRes = new JDExpressTools().createOrder(model);
            if (jdRes != null && jdRes.getResult().getSuccess()) {
                // 更新订单表状态
                String waybillCode = jdRes.getResult().getData().getWaybillCode();
                return CommonResult.success(waybillCode);
            }
            return CommonResult.failed("物流订单创建失败");

        }
        return CommonResult.failed("获取订单失败");

    }
    @PostMapping("/sendOrder/{orderId}")
    private CommonResult<Object> sendOrder(@PathVariable("orderId") String orderId) {
        JDExpressModel model = new JDExpressModel();
        HashMap<String, Object> map = new HashMap<>();
        map.put("order_id", orderId);
        List<ShopOrder> orders = shopOrderMapper.selectByMap(map);
        if (orders != null && !orders.isEmpty()) {
            ShopOrder shopOrder = orders.get(0);

            // 调用京东物流
            model.setOrderId(shopOrder.getOrderNo()+"02");
            model.setVolume(10);
            model.setWeight(1);

            Map<String, String> config = getConfig();
            // 基础配置
            assert config != null;
            model.setAppKey(config.get("appKey"));
            model.setAccessToken(config.get("accessToken"));
            model.setAppSecret(config.get("appSecret"));
            model.setCustomCode(config.get("customCode"));

            // 配置收件人信息
            model.setReceiveUser(shopOrder.getTakerName());
            model.setReceiveMobile(shopOrder.getTakerMobile());
            model.setReceiveAddress(shopOrder.getTakerFullAddress());

            // 获取并配置发件人信息
            ShopAddress address = addressMapper.selectById(1);
            model.setSendUser(address.getContactName());
            model.setSendMobile(address.getMobile());
            model.setSendAddress(address.getFullAddress());

            // 生成物流单号
            EcapV1OrdersCreateLopResponse jdRes = new JDExpressTools().createOrder(model);
            if (jdRes != null && jdRes.getResult().getSuccess()) {
                // 更新订单表状态
                String waybillCode = jdRes.getResult().getData().getWaybillCode();
                shopOrder.setResend(0);
                shopOrderMapper.updateById(shopOrder);

                // 更新物流表信息
                ShopOrderDelivery delivery = new ShopOrderDelivery();
                delivery.setOrderId(shopOrder.getOrderId());
                delivery.setDeliveryType("express");
                delivery.setSubDeliveryType("express");
                delivery.setExpressCompanyId(10);
                delivery.setName("衣服");
                delivery.setExpressNumber(waybillCode);
                delivery.setCreateTime(System.currentTimeMillis() /1000);
                delivery.setRemark("发往客户手中");
                deliveryMapper.insert(delivery);
                return CommonResult.success(null);
            }
            return CommonResult.failed("物流订单创建失败");

        }
        return CommonResult.failed("获取订单失败");

    }
}
